package com.um.jdy.platform.device.manger;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.io.FileUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.core.util.ZipUtil;
import cn.hutool.extra.qrcode.QrCodeUtil;
import cn.hutool.extra.qrcode.QrConfig;
import com.google.zxing.qrcode.decoder.ErrorCorrectionLevel;
import com.um.jdy.common.base.enums.YesOrNo;
import com.um.jdy.common.device.entity.dto.CodeDTO;
import com.um.jdy.common.device.entity.po.Code;
import com.um.jdy.common.device.entity.vo.CodeVO;
import com.um.jdy.common.device.service.CodeService;
import com.um.jdy.common.device.utils.DrawUtil;
import com.um.jdy.common.platform.code.PlatformCode;
import com.um.jdy.common.platform.entity.po.Company;
import com.um.jdy.common.platform.service.AppSettingService;
import com.um.jdy.common.platform.service.CompanyService;
import com.um.jdy.platform.device.entity.dto.CodePageDTO;
import com.um.springboot.starter.orm.entity.Response;
import com.um.springboot.starter.orm.manager.BasePlusManager;
import com.um.springboot.starter.orm.params.ExportParams;
import com.um.springboot.starter.orm.params.ListDTO;
import com.um.springboot.starter.utils.ExcelUtil;
import com.um.springboot.starter.utils.StringUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import java.awt.image.BufferedImage;
import java.io.File;
import java.util.*;

/**
 * 管理类：充电桩二维码
 */
@Component
public class PileCodeManager extends BasePlusManager<CodeService, Code, CodeDTO, CodeVO,CodePageDTO, ListDTO> {

    @Autowired
    AppSettingService appSettingService;

    @Autowired
    CompanyService companyService;

    /**
     * 生成充电桩二维码
     *
     * @param prefixName
     * @param num
     * @return
     */
    @Transactional
    public Response generateCode(String prefixName, Integer num) {

        Company company = companyService.getEntity("platform_id",getComId());
        if(company == null){
            Response.failed(PlatformCode.PlatformNotExist);
        }

        String prefixCode = DateUtil.format(new Date(), "yy") + company.getCode();
        List<Code> list = service.getViewModelList("get_max_code",Code.class,new Object[]{prefixCode+"%"});

        int startCode = 1;
        if (list.size() > 0) {
            String code = list.get(0).getCode();
            startCode = StringUtil.toInt(code.substring(5)) + 1;
        }

        for (int index = 0; index < num; index++) {
            String deviceCode = String.format("%05d", startCode);
            Code entity = new Code();
            entity.setName(prefixName + "_" + prefixCode + deviceCode);
            entity.setCode(prefixCode + deviceCode);

            String domain = StringUtil.isEmpty(company.getUserDomain()) ? company.getDomain() : company.getUserDomain();

            entity.setQrcode("https://"+domain+"/qr?c=" + prefixCode + deviceCode);
            entity.setCreateTime(new Date());
            entity.setStatus(YesOrNo.No.name());
            service.save(entity);

            startCode++;
        }
        return Response.success();
    }

    /**
     * 导出二维码
     *
     * @param exportParams
     * @return
     */
    public Response exportCodePage(ExportParams exportParams){

        exportParams.getCondition().put("orderby","code asc");
        List<Code> list = service.getListByLike(exportParams.getProperties(), exportParams.getValues(), exportParams.getRangeEntitys(),
                exportParams.getOrderNames(), exportParams.getSortOns(), exportParams.getStart(), exportParams.getLimit());

        Map<String,String> mapFormat = new Hashtable<>();

        String fileName = "Excel"+ com.um.springboot.starter.utils.DateUtil.getDateString(new Date(), "yyyyMMddHHmmss")+".xls";
        String path = service.getExportFilePath(fileName);
        List<String> columns = Arrays.asList("设备名称","设备编号","二维码字符串");
        List<String> properties = Arrays.asList("name","code","qrcode");
        ExcelUtil.writeEntity(path, columns, list, properties, exportParams.getMapParam(), mapFormat, exportParams.getMapZero(),true);

        return Response.success(service.getDownFilePath(fileName));
    }

    /**
     * 导出二维码
     *
     * @param exportParams
     * @return
     */
    public Response exportQrcode(ExportParams exportParams) {

        exportParams.getCondition().put("orderby","code asc");
        List<Code> list = service.getListByLike(exportParams.getProperties(), exportParams.getValues(), exportParams.getRangeEntitys(),
                exportParams.getOrderNames(), exportParams.getSortOns(), exportParams.getStart(), exportParams.getLimit());

        String dirName = "qrcode" + DateUtil.format(new Date(), "yyyyMMddHHmmss");
        String dirPath = service.getExportFilePath(dirName);
        QrConfig qrConfig = QrConfig.create().setErrorCorrection(ErrorCorrectionLevel.Q);

        boolean hasFile = false;
        for (Code row : list) {
            String code = row.getCode();
            String qrcode = row.getQrcode();
            if ("".equals(code) || "".equals(qrcode)) {
                continue;
            }

            String targetPath = StrUtil.builder(dirPath, "/", code, ".png").toString();
            BufferedImage bufferedImage = QrCodeUtil.generate(qrcode, qrConfig);
            DrawUtil.drawQrcodeNo(bufferedImage, code, targetPath);

            hasFile = true;
        }

        if (!hasFile) {
            return Response.success("");
        }

        String zipPath = dirPath + ".zip";
        ZipUtil.zip(new File(zipPath), false, new File(dirPath));
        FileUtil.del(dirPath);

        return Response.success(service.getDownFilePath(dirName + ".zip"));
    }

    /**
     * 导出插座二维码
     *
     * @param exportParams
     * @return
     */
    public String exportSocketQrcode(ExportParams exportParams,int portNum) {
        exportParams.getCondition().put("orderby","code asc");

        List<Code> list = service.getListByLike(exportParams.getProperties(), exportParams.getValues(), exportParams.getRangeEntitys(),
                exportParams.getOrderNames(), exportParams.getSortOns(), exportParams.getStart(), exportParams.getLimit());

        String dirName = "qrcode" + com.um.springboot.starter.utils.DateUtil.getDateString(new Date(), "yyyyMMddHHmmss");
        String dirPath = service.getExportFilePath(dirName);
        QrConfig qrConfig = QrConfig.create().setErrorCorrection(ErrorCorrectionLevel.Q);

        boolean hasFile = false;
        for (Code row : list) {
            String code = row.getCode();
            String qrcode = row.getQrcode();
            if ("".equals(code) || "".equals(qrcode)) {
                continue;
            }

            for (int index = 1; index <=  portNum; index++) {
                String socketCode = code + index;
                String targetPath = StrUtil.builder(dirPath, "/", socketCode, ".png").toString();
                BufferedImage bufferedImage = QrCodeUtil.generate(qrcode + "&g=" + index, qrConfig);
                DrawUtil.drawQrcodeNo(bufferedImage, socketCode, targetPath);

                hasFile = true;
            }
        }

        if (!hasFile) {
            return "";
        }

        String zipPath = dirPath + ".zip";
        ZipUtil.zip(new File(zipPath), false, new File(dirPath));
        FileUtil.del(dirPath);

        return "/export/" + dirName + ".zip";
    }
}
